<template>
  <div class="mod-user">
    <div class="listHead">
      <p v-if="status == 0">
        <el-button type="text" @click="saveForm()"
          >保存</el-button>
        <el-button type="text" @click="checkForm()"
          >选单</el-button>
        <!-- <el-button type="text" @click="goback"
          >返回</el-button> -->
      </p>
      <p v-else>
        <el-button
          type="text"
          v-if="dataForm.status == 0"
          @click="deleteHandle(dataForm.id)"
          >删除</el-button
        >
        <el-button @click="addHandle()">新增</el-button>
        <el-button
          type="text"
          v-if="dataForm.status == 0"
          @click="examineHandle(dataForm.id)"
          >审核</el-button>
        <el-button
          type="text"
          v-if="dataForm.status == 1"
          @click="unexamineHandle(dataForm.id)"
          >反审</el-button>
        <el-dropdown v-if="dataForm.status == 1">
          <span class="el-dropdown-link">
            生单<i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              ><span @click="gootherin">其他入库</span></el-dropdown-item
            >
            <el-dropdown-item
              ><span @click="gootherout">其他出库</span></el-dropdown-item
            >
          </el-dropdown-menu>
        </el-dropdown>

        <!-- <el-button type="text" @click="goback"
          >返回</el-button> -->
      </p>
    </div>
    <div class="headInfo">
      <el-form
        :inline="true"
        :model="dataForm"
        ref="dataForm"
        :rules="dataFormRule"
        @keyup.enter.native="getDataList()"
      >
        <el-form-item
          ><em>单据编号</em>
          <div v-if="status == 0">
            <el-input
              v-model="dataForm.number"
              placeholder="单据编号"
              :disabled="true"
            ></el-input>
          </div>
          <div v-else class="see">
            <el-input
              v-model="dataForm.number"
              placeholder="单据编号"
              :disabled="true"
            ></el-input>
          </div>
        </el-form-item>
        <el-form-item>
          <em>单据日期</em>
          <div class="block" v-if="status == 0">
            <el-date-picker
              v-model="dataForm.dateTime"
              type="datetime"
              placeholder="选择日期时间"
              :disabled="true"
            >
            </el-date-picker>
          </div>
          <div v-else class="see">
            <el-date-picker
              v-model="dataForm.dateTime"
              type="datetime"
              placeholder="选择日期时间"
              :disabled="true"
            >
            </el-date-picker>
          </div>
        </el-form-item>
        <el-form-item
          ><em>源单</em>
          <div v-if="status == 0">
            <el-input
              v-model="dataForm.salesBillNo"
              placeholder="源单"
            ></el-input>
          </div>
          <div v-else class="see">
            <el-input
              v-model="dataForm.salesBillNo"
              placeholder="源单"
              :disabled="true"
            ></el-input>
          </div>
        </el-form-item>
        <el-form-item class="is-required" label="" prop="customer">
          <em>客户</em>
          <div v-if="status == 0">
            <el-input
              v-model="dataForm.customer"
              placeholder="客户"
              clearable
              @click.native="goCustomer"
              suffix-icon="el-icon-search"
              readonly
            ></el-input>
          </div>
          <div v-else class="see">
            <el-input
              v-model="dataForm.customer"
              placeholder="客户"
              clearable
              @click.native="goCustomer"
              suffix-icon="el-icon-search"
              readonly
              :disabled="true"
            ></el-input>
          </div>
        </el-form-item>
        <el-form-item class="is-required" prop="billType"
          ><em>发票类型</em>
          <div v-if="status == 0">
            <el-select
              clearable
              v-model="dataForm.billType"
              placeholder="发票类型请选择"
            >
              <el-option
                v-for="item in options3"
                :key="item.value"
                :label="item.label"
                :value="item"
              >
              </el-option>
            </el-select>
          </div>
          <div v-else class="see">
            <el-select
              clearable
              v-model="dataForm.billType"
              placeholder="发票类型请选择"
              :disabled="true"
            >
              <el-option
                v-for="item in options3"
                :key="item.value"
                :label="item.label"
                :value="item"
              >
              </el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item class="is-required" prop="salesman"
          ><em>业务员</em>
          <div v-if="status == 0">
            <el-select
              v-model="dataForm.salesman"
              placeholder="业务员请选择"
              clearable
            >
              <!-- @change="change1($event)" -->
              <el-option
                v-for="item in options1"
                :key="item.value"
                :label="item.label"
                :value="item"
              >
              </el-option>
            </el-select>
          </div>
          <div v-else class="see">
            <el-select
              v-model="dataForm.salesman"
              placeholder="业务员请选择"
              clearable
              :disabled="true"
            >
              <!-- @change="change1($event)" -->
              <el-option
                v-for="item in options1"
                :key="item.value"
                :label="item.label"
                :value="item"
              >
              </el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item
          ><em>退货日期</em>
          <div v-if="status == 0">
            <el-date-picker
              v-model="dataForm.salesDate"
              type="date"
              placeholder="选择日期"
            >
            </el-date-picker>
          </div>
          <div v-else class="see">
            <el-date-picker
              v-model="dataForm.salesDate"
              type="date"
              placeholder="选择日期"
              :disabled="true"
            >
            </el-date-picker>
          </div>
        </el-form-item>
        <el-form-item
          ><em>退货地址</em>
          <div v-if="status == 0">
            <el-input
              v-model="dataForm.salesAddress"
              placeholder="退货地址"
            ></el-input>
          </div>
          <div v-else class="see">
            <el-input
              v-model="dataForm.salesAddress"
              placeholder="退货地址"
              :disabled="true"
            ></el-input>
          </div>
        </el-form-item>
        <el-form-item
          ><em>退货联系人</em>
          <div v-if="status == 0">
            <el-input
              v-model="dataForm.salesContacts"
              placeholder="退货联系人"
            ></el-input>
          </div>
          <div v-else class="see">
            <el-input
              v-model="dataForm.salesContacts"
              placeholder="退货联系人"
              :disabled="true"
            ></el-input>
          </div>
        </el-form-item>
        <el-form-item
          ><em>退货联系电话</em>
          <div v-if="status == 0">
            <el-input
              v-model="dataForm.salesPhoneNum"
              placeholder="退货联系电话"
            ></el-input>
          </div>
          <div v-else class="see">
            <el-input
              v-model="dataForm.salesPhoneNum"
              placeholder="退货联系电话"
              :disabled="true"
            ></el-input>
          </div>
        </el-form-item>
        <el-form-item class="is-required" prop="payType"
          ><em>退款方式</em>
          <div v-if="status == 0">
            <el-select
              v-model="dataForm.payType"
              placeholder="退款方式请选择"
              clearable
            >
              <el-option
                v-for="item in options2"
                :key="item.value"
                :label="item.label"
                :value="item"
              >
              </el-option>
            </el-select>
          </div>
          <div v-else class="see">
            <el-select
              v-model="dataForm.payType"
              placeholder="退款方式请选择"
              clearable
              :disabled="true"
            >
              <el-option
                v-for="item in options2"
                :key="item.value"
                :label="item.label"
                :value="item"
              >
              </el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item class="saleList"
          ><em>外部单据号</em>
          <div v-if="status == 0">
            <el-input
              v-model="dataForm.externalNumber"
              placeholder="外部单据号"
              clearable
            ></el-input>
          </div>
          <div v-else class="see">
            <el-input
              v-model="dataForm.externalNumber"
              placeholder="外部单据号"
              clearable
              :disabled="true"
            ></el-input>
          </div>
        </el-form-item>
        <el-form-item class="is-required" prop="serviceType"
          ><em>业务项目</em>
          <div v-if="status == 0">
            <el-select
              clearable
              v-model="dataForm.serviceType"
              placeholder="业务项目请选择"
            >
              <el-option
                v-for="item in options4"
                :key="item.value"
                :label="item.label"
                :value="item"
              >
              </el-option>
            </el-select>
          </div>
          <div v-else class="see">
            <el-select
              clearable
              v-model="dataForm.serviceType"
              placeholder="业务项目请选择"
              :disabled="true"
            >
              <el-option
                v-for="item in options4"
                :key="item.value"
                :label="item.label"
                :value="item"
              >
              </el-option>
            </el-select>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="main" v-if="status == 0">
      <el-form
        ref="dataList"
        size="small"
        class="form1"
        :model="dataForm"
        :rules="dataListRule"
      >
        <template>
          <el-table
            :data="dataForm.dataList"
            border
            v-loading="dataListLoading"
            @selection-change="selectionChangeHandle"
            style="width: 100%"
            :summary-method="getSummaries"
            show-summary
          >
            <el-table-column
              label="序号"
              type="index"
              align="center"
              show-overflow-tooltip
              width="50px"
            >
            </el-table-column>
            <el-table-column
              prop="mBarCode"
              header-align="center"
              align="center"
              label="货品编号"
              class="mBarCode"
            >
              <template slot-scope="scope">
                <el-form-item
                  :prop="'dataList.' + scope.$index + '.mBarCode'"
                  :rules="dataListRule.mBarCode"
                >
                  <el-input
                    style="width: 100%"
                    placeholder="请选择"
                    v-model="scope.row.mBarCode"
                    :suffix-icon="
                      showTree ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
                    "
                    @click.native="deptogglePanel(scope.$index)"
                    size="medium"
                    @input="input($event)"
                    readonly
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              header-align="center"
              align="center"
              label="货品名称"
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row.name" :disabled="true"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="standard"
              header-align="center"
              align="center"
              label="规格型号"
            >
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.standard"
                  :disabled="true"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="DepotName"
              header-align="center"
              align="center"
              label="仓库"
            >
              <template slot-scope="scope">
                <el-form-item
                  :prop="'dataList.' + scope.$index + '.DepotName'"
                  :rules="dataListRule.DepotName"
                >
                  <el-select
                    v-model="scope.row.DepotName"
                    clearable
                    @change="change($event, scope.$index)"
                  >
                    <el-option
                      v-for="item in DepotOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              prop="number"
              header-align="center"
              align="center"
              label="数量"
            >
              <template slot-scope="scope">
                <el-input v-model.number="scope.row.number"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="unit"
              header-align="center"
              align="center"
              label="计量单位"
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row.unit" :disabled="true"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="tax"
              header-align="center"
              align="center"
              label="税率"
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row.tax" :disabled="true"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="lowDecimal"
              header-align="center"
              align="center"
              label="含税单价"
            >
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.lowDecimal"
                  :disabled="true"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="AllPrice" label="含税金额">
              <template scope="scope">
                <el-input
                  size="mini"
                  :value="Pricefloat(scope.$index)"
                  :disabled="true"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="stock"
              header-align="center"
              align="center"
              label="现存量"
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row.stock" :disabled="true"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="remark"
              header-align="center"
              align="center"
              label="备注"
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row.remark"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              header-align="center"
              align="center"
              label="操作"
              width="170px"
              v-if="status == 0"
            >
              <template slot-scope="scope">
                <el-button
                  v-if="isAuth('sys:user:update')"
                  type="text"
                  size="small"
                  @click="addRow"
                  >增行</el-button
                >
                <el-button
                  v-if="isAuth('sys:user:delete')"
                  type="text"
                  size="small"
                  @click="deleteRow(scope.$index, dataForm.dataList)"
                  style="color: #FA7F05;"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-form>
    </div>
    <div class="main" v-else>
      <el-form
        ref="dataList"
        size="small"
        class="form1"
        :model="dataForm"
        :rules="dataListRule"
      >
        <template>
          <el-table
            :data="dataForm.dataList"
            border
            v-loading="dataListLoading"
            @selection-change="selectionChangeHandle"
            style="width: 100%"
            :summary-method="getSummaries"
            show-summary
          >
            <el-table-column
              label="序号"
              type="index"
              align="center"
              show-overflow-tooltip
              width="50px"
            >
            </el-table-column>
            <el-table-column
              prop="mBarCode"
              header-align="center"
              align="center"
              label="货品编号"
              class="mBarCode"
            >
            </el-table-column>
            <el-table-column
              prop="name"
              header-align="center"
              align="center"
              label="货品名称"
            >
            </el-table-column>
            <el-table-column
              prop="standard"
              header-align="center"
              align="center"
              label="规格型号"
            >
            </el-table-column>
            <el-table-column
              prop="DepotName"
              header-align="center"
              align="center"
              label="仓库"
            >
            </el-table-column>
            <el-table-column
              prop="number"
              header-align="center"
              align="center"
              label="数量"
            >
            </el-table-column>
            <el-table-column
              prop="unit"
              header-align="center"
              align="center"
              label="计量单位"
            >
            </el-table-column>
            <el-table-column
              prop="tax"
              header-align="center"
              align="center"
              label="税率"
            >
            </el-table-column>
            <el-table-column
              prop="lowDecimal"
              header-align="center"
              align="center"
              label="含税单价"
            >
            </el-table-column>
            <el-table-column prop="AllPrice" label="含税金额">
            </el-table-column>
            <el-table-column
              prop="stock"
              header-align="center"
              align="center"
              label="现存量"
            >
            </el-table-column>
            <el-table-column
              prop="remark"
              header-align="center"
              align="center"
              label="备注"
            >
            </el-table-column>
          </el-table>
        </template>
      </el-form>
    </div>
    <div class="footer" v-if="status == 0">
      <el-input
        type="textarea"
        :rows="5"
        placeholder="请输入备注"
        v-model="dataForm.remark"
        resize="none"
      >
      </el-input>
    </div>
    <div class="footer" v-else :class="dataForm.remark?'remarkFooter':''">
      {{ dataForm.remark }}
    </div>
    <goodsListDialog
      v-if="isfind"
      :isfind="isfind"
      @changeFind="getFind"
      @getGoods="getGoodsinfo"
    ></goodsListDialog>
    <customerDialog
      v-if="isCustomer"
      :isCustomer="isCustomer"
      @changeCustomer="getCustomer"
      @getCustomer="getCustomerinfo"
    ></customerDialog>
    <checkForm
      v-if="ischeckForm"
      :ischeckForm="ischeckForm"
      :istype="istype"
      @changecheckForm="getcheckForm"
      @getGoods="getcheckGoods"
      @goodsinfo="getcheckgoodsinfo"
    ></checkForm>
  </div>
</template>
<script>
import goodsListDialog from "@/views/common/goodsListDialog";
import customerDialog from "@/views/common/customerDialog";
import checkForm from "@/views/common/checkForm";
export default {
  components: {
    goodsListDialog,
    customerDialog,
    checkForm,
  },
  data() {
    return {
      dataForm: {
        number: "",
        dateTime: "",
        salesBillNo: "",
        salesman: "",
        customer: "",
        billType: "",
        salesman: "",
        salesDate: "",
        salesAddress: "",
        salesContacts: "",
        salesPhoneNum: "",
        payType: "",
        status: "",
        serviceType: "",
        transportType: "",
        externalNumber: "",
        remark: "",
        dataList: [],
      },
      status: 0,
      time: "",
      dataList: [],
      DepotOptions: [],
      ischeckForm: false,
      options2: [
        {
          value: "选项1",
          label: "支付宝",
        },
        {
          value: "选项2",
          label: "微信",
        },
        {
          value: "选项3",
          label: "现金",
        },
        {
          value: "选项4",
          label: "转账",
        },
      ],
      options4: [
        {
          value: "选项1",
          label: "线上",
        },
        {
          value: "选项2",
          label: "线下",
        },
      ],
      options3: [
        {
          value: "选项1",
          label: "专用发票",
        },
        {
          value: "选项2",
          label: "普通发票",
        },
      ],
      pageIndex: 1,
      istype: 2,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      isfind: false,
      isCustomer: false,
      iscustomer: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      value1: [],
      options1: [],
      beginTime: "",
      endTime: "",
      index: "",
      dataFormRule: {
        customer: [{ required: true, message: " ", trigger: "change" }],
        billType: [{ required: true, message: " ", trigger: "change" }],
        salesman: [{ required: true, message: " ", trigger: "change" }],
        payType: [{ required: true, message: " ", trigger: "change" }],
        serviceType: [{ required: true, message: " ", trigger: "change" }],
      },
      dataListRule: {
        mBarCode: [{ required: true, message: " ", trigger: "change" }],
        DepotName: [{ required: true, message: " ", trigger: "change" }],
      },
      showTree: false,
      organId: "",
    };
  },
  activated() {
    this.getData();
    this.salesman();
    this.getGoodsinfo();
    this.getCustomerinfo();
    this.getDepotOptions();
    this.getcheckGoods();
    this.getcheckgoodsinfo();
  },
  methods: {
        addHandle() {
      this.$router.push({
        path: "/sale-saleout/saleadd",
      });
      this.getData();
    },
    // 删除
    deleteHandle(ids) {
      this.$http({
        url: this.$http.adornUrl(`/depotHead/deleteDepotHeadAndDetail`),
        method: "get",
        params: this.$http.adornParams({
          id: ids,
        }),
      }).then(({ data }) => {
        console.log("data is :", data);
        if (data && data.code === 0) {
          this.$message({
            message: "操作成功",
            type: "success",
            duration: 1500,
          });
          this.removeTabHandle(this.mainTabsActiveName);
        }
      });
    },
    getcheckgoodsinfo(val){
      console.log(val)
      if(val){
        this.dataForm.dataList=val
      }
    },
    getcheckGoods(val){
      console.log(val)
      if(val){
        this.dataForm.deliveryBillNo = val.defaultNumber
        this.dataForm.customer = val.organName
        this.dataForm.salesman = val.userName
        this.dataForm.address = val.deliverAddress
        this.dataForm.phoneNum = val.phoneNum
        this.dataForm.salesBillNo = val.defaultNumber
        this.dataForm.serviceType = val.serviceType
        this.dataForm.transportType = val.transportType
        this.dataForm.transportType = val.transportType
        this.dataForm.organId = val.organId
      }
    },
    getcheckForm(val) {
      console.log(val);
      this.ischeckForm = false;
    },
    checkForm(){
      console.log(111)
      this.ischeckForm = true;
    },
    // 反审核
    unexamineHandle(id) {
      this.$http({
        url: this.$http.adornUrl(`/depotHead/batchSetStatus`),
        method: "post",
        data: this.$http.adornData(
          {
            depotHeadIDs: id.toString(),
            status: "0",
          },
          false
        ),
      }).then(({ data }) => {
        // console.log("data is :", data);
        if (data && data.code === 0) {
          this.$message({
            message: "操作成功",
            type: "success",
            duration: 1500,
            onClose: () => {
              this.getData();
            },
          });
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    // 审核
    examineHandle(id) {
      console.log(typeof id);
      this.$http({
        url: this.$http.adornUrl(`/depotHead/batchSetStatus`),
        method: "post",
        data: this.$http.adornData(
          {
            depotHeadIDs: id.toString(),
            status: "1",
          },
          false
        ),
      }).then(({ data }) => {
        // console.log("data is :", data);
        if (data && data.code === 0) {
          this.$message({
            message: "操作成功",
            type: "success",
            duration: 2000,
            onClose: () => {
              this.getData();
            },
          });
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    // 获取业务员下拉
    salesman() {
      this.$http({
        url: this.$http.adornUrl(`/depot/getAllUser`),
        method: "get",
      }).then((data) => {
        console.log(data);
        let res = JSON.parse(JSON.stringify(data.data.data));
        res = res.filter((item) => {
          return (item.value = item.user_id), (item.label = item.username);
        });
        this.options1 = res;
      });
    },
    // 尾行合计
    getSummaries(param) {
      console.log(param)
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        if (index === 1) {
          sums[index] = "";
          return;
        }
        if (index === 2) {
          sums[index] = "";
          return;
        }
        if (index === 3) {
          sums[index] = "";
          return;
        }
        if (index === 4) {
          sums[index] = "";
          return;
        }
        if (index === 6) {
          sums[index] = "";
          return;
        }
        if (index === 7) {
          sums[index] = "";
          return;
        }
        if (index === 8) {
          sums[index] = "";
          return;
        }
        if (index === 10) {
          sums[index] = "";
          return;
        }
        if (index === 11) {
          sums[index] = "";
          return;
        }
        if (index === 12) {
          sums[index] = "";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += "";
        } else {
          sums[index] = "N/A";
        }
      });
      return sums;
    },
    //总价的依赖属性
    Pricefloat(index) {
      this.dataForm.dataList[index].AllPrice =
        this.dataForm.dataList[index].lowDecimal *
        this.dataForm.dataList[index].number;
      return (
        this.dataForm.dataList[index].lowDecimal *
          this.dataForm.dataList[index].number || null
      );
    },
    // 选择仓库
    change(e, index) {
      console.log(e, index);
      if (this.dataForm.dataList[index].mBarCode == "") {
        return;
      }
      // this.getstock(e.id, this.dataForm.dataList[index].MaterialExtendId);
    },
    // 获取库存信息
    // getstock(depotId, mId) {
    //   this.$http({
    //     url: this.$http.adornUrl(
    //       `/depotItem/findStockNumById?depotId=${depotId}&mId=${mId}`
    //     ),
    //     method: "get",
    //   }).then(({ data }) => {
    //     console.log(data);
    //     this.dataForm.dataList[this.curSelectIndex].Stock = data.data.stock;
    //   });
    // },
    // 获取仓库信息
    getDepotOptions() {
      this.$http({
        url: this.$http.adornUrl("/depot/findDepotByUserId"),
        method: "get",
        params: this.$http.adornParams({
          UBType: "UserDepot",
          UBKeyId: 63,
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.DepotOptions = data.data.filter((fitem) => {
            fitem.value = fitem.id;
            fitem.label = fitem.depotName;
            return fitem;
          });
        }
      });
    },
    // 获取传过来的商品信息
    getGoodsinfo(val) {
      console.log(val);
      if (!val) {
        return;
      }
      this.dataForm.dataList[this.index].name = val.name;
      this.dataForm.dataList[this.index].meId = val.meId;
      this.dataForm.dataList[this.index].mBarCode = val.mBarCode;
      this.dataForm.dataList[this.index].standard = val.standard;
      this.dataForm.dataList[this.index].unit = val.unit;
      this.dataForm.dataList[this.index].remark = val.remark;
      this.dataForm.dataList[this.index].lowDecimal = val.lowDecimal;
      this.dataForm.dataList[this.index].stock = val.stock;
      this.dataForm.dataList[this.index].number = 1;
      console.log(this.dataForm.dataList[this.index].name);
      console.log(val.stock);
    },
    // 获取传过来的客户信息
    getCustomerinfo(val) {
      if (!val) {
        return;
      }
      console.log(val);
      this.dataForm.customer = val.supplier;
      this.dataForm.salesContacts = val.contacts;
      this.dataForm.salesContacts = val.contacts;
      this.dataForm.salesPhoneNum = val.phoneNum;
      this.organId = val.id;

      console.log(this.dataForm.customer);
    },
    // 获取传过来的商品信息
    getFind(val) {
      console.log(val);
      this.isfind = val;
    },
    deptogglePanel(index) {
      this.index = index;
      this.isfind = true;
    },
    // 获取传过来的客户信息
    getCustomer(val) {
      console.log(val);
      this.isCustomer = false;
    },
    goCustomer() {
      this.isCustomer = true;
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val;
    },
    // 表格默认有一行 增行
    addRow() {
      this.dataForm.dataList.push({
        mBarCode: "",
        name: "",
        standard: "",
        DepotName: "",
        number: "",
        unit: "",
        tax: "",
        lowDecimal: "",
        stock: "",
        remark: "",
        AllPrice: "",
      });
    },
    // 插行
    insertRow(index, rows) {
      rows.splice(index + 1, 0, {
        mBarCode: "",
        name: "",
        standard: "",
        DepotName: "",
        number: "",
        unit: "",
        tax: "",
        lowDecimal: "",
        stock: "",
        remark: "",
      });
    },
    // 复制
    copyRow(index, rows, row) {
      // console.log(index, rows, row)
      rows.splice(index + 1, 0, row);
    },
    // 删除
    deleteRow(index, rows) {
      //删除改行
      rows.splice(index, 1);
    },
    // 获取页面数据
    getData() {
      console.log(this.$route.query.update);
      if (this.$route.query.id) {
        let subType = "销售退货";
        let roleType = "全部数据";
        let str = `{"type":"入库","subType":"${subType}","roleType":"${roleType}","state":"","number":"","beginTime":"","endTime":"","materialParam":"","userName":"","payType":"","serviceType":"","transportType":"","status":"","depotIds":"","deliverDate":"","salesDate":"","billType":"","externalNumber":"","stockType":"","deliveryType":"",deliveryBillNo:"",salesBillNo:"","buyer":"","organName":"","purchaseStockBillNo":"","purchaseSalesBillNo":"",accountSalesBillno:""}`;
        var search = encodeURIComponent(str);
        this.$http({
          url: this.$http.adornUrl(`/depotHead/list?search=${search}`),
          method: "get",
          params: this.$http.adornParams({
            currentPage: 1,
            pageSize: 100000,
          }),
        }).then(({ data }) => {
          data.data.list.map((item) => {
            // console.log(item)
            if (item.id == this.$route.query.id) {
              // this.dataForm=item
              this.dataForm.number = item.number;
              this.dataForm.deliverDate = item.deliverDate;
              this.dataForm.dateTime = item.operTime;
              this.dataForm.customer = item.organName;
              this.dataForm.salesman = item.userName;
              this.dataForm.salesAddress = item.salesAddress;
              this.dataForm.billType = item.billType;
              this.dataForm.id = item.id;
              this.dataForm.status = item.status;
              this.dataForm.organId = item.organId;
              this.dataForm.salesDate = JSON.parse(
                JSON.stringify(item.salesDate)
              );
              this.dataForm.remark = item.remark;
              this.dataForm.salesContacts = item.salesContacts;
              this.dataForm.salesPhoneNum = item.salesPhoneNum;
              this.dataForm.salesBillNo = item.salesBillNo;
              this.dataForm.serviceType = item.serviceType;
              this.dataForm.payType = item.payType;
              this.dataForm.externalNumber = item.externalNumber;
              this.time = JSON.parse(JSON.stringify(item.salesDate));
            }
          });
        });
        this.$http({
          url: this.$http.adornUrl(`/depotItem/getDetailList`),
          method: "get",
          params: this.$http.adornParams(
            {
              headerId: this.$route.query.id,
              mpList: "undefined%2Cundefined%2Cundefined",
            },
            false
          ),
        }).then(({ data }) => {
          console.log(data.data.rows);
          let dataList = JSON.parse(JSON.stringify(data.data.rows));
          dataList.map((item) => {
            // this.addRow()
            item.mBarCode = item.MaterialName.split("_")[0];
            item.name = item.MaterialName.split("_")[1].split("(")[0];
            item.standard = item.MaterialName.split("_")[1]
              .split("(")[1]
              .split(")")[0];
            item.number = item.OperNumber;
            item.unit = item.Unit;
            item.tax = item.TaxRate;
            item.lowDecimal = item.UnitPrice;
            item.stock = item.Stock;
            item.remark = item.Remark;
          });
          this.dataForm.dataList = dataList;
        });
        if (this.$route.query.update) {
          this.status = 0;
        } else {
          console.log(222);
          this.status = 1;
        }
      } else {
            this.status = 0;
        if (this.$route.query.gosalein) {
            console.log(11111)
        } else {
            this.dataForm.customer = ""
            this.dataForm.salesBillNo = ""
            this.dataForm.billType = ""
            this.dataForm.salesman = ""
            this.dataForm.salesDate = ""
            this.dataForm.salesAddress = ""
            this.dataForm.salesContacts = ""
            this.dataForm.salesPhoneNum = ""
            this.dataForm.payType = ""
            this.dataForm.externalNumber = ""
            this.dataForm.serviceType = ""
            this.dataForm.dataList = []
            if(this.dataForm.dataList.length>0){

            }else{
              this.addRow();
            }
        }
          let num = "";
          this.$http({
            url: this.$http.adornUrl("/depotHead/buildNumber"),
            method: "get",
          }).then(({ data }) => {
            num = "XSTH" + data.DefaultNumber;
            this.$set(this.dataForm, "number", num);
          });
          this.$set(this.dataForm, "dateTime", new Date());
      }
    },
    // 生单
    dataFormSubmit() {},
    // 保存
    saveForm() {
      console.log(this.dataForm.salesDate=="")
      if (this.dataForm.salesDate) {
        console.log(this.timestampToTime(this.dataForm.salesDate.getTime()))
      }
      let dataFormvalid = null;
      let dataListvalid = null;
      this.$refs["dataForm"].validate((valid1) => {
        dataFormvalid = valid1;
      });
      this.$refs["dataList"].validate((valid2) => {
        dataListvalid = valid2;
      });
      if (dataFormvalid && dataListvalid) {
        if (this.$route.query.id) {
          if (this.dataForm.salesDate) {
            if (this.time == this.dataForm.salesDate) {
              console.log(111);
              var salesDate = this.dataForm.salesDate;
            } else {
              console.log(222);
              var salesDate = this.timestampToTime1(
                this.dataForm.salesDate.getTime()
              );
            }
          } else {
            console.log(333);
            var salesDate = "";
          }
          console.log(this.dataForm.serviceType);
          console.log(this.dataForm.serviceType.label);
          let info = `{"Type":"入库","SubType":"销售退货","DefaultNumber":"${
            this.dataForm.number
          }","Number":"${this.dataForm.number}","LinkNumber":"","OperTime":"${
            this.dataForm.dateTime
          }","salesDate":"${salesDate}","OrganId":"${
            this.organId || ""
          }","serviceType":"${
            this.dataForm.serviceType.label || this.dataForm.serviceType
          }","salesBillNo":"${this.dataForm.salesBillNo}","externalNumber":"${
            this.dataForm.externalNumber
          }",username:"${
            this.dataForm.salesman.label || this.dataForm.salesman
          }","Salesman":"","AccountId":"${
            this.accountId || ""
          }","deliverDate":"",billType:"${
            this.dataForm.billType.label || this.dataForm.billType
          }","ChangeAmount":${this.AllPrice},"TotalPrice":"${
            this.AllPrice
          }","salesAddress":"${this.dataForm.salesAddress}","salesContacts":"${
            this.dataForm.salesContacts
          }","salesPhoneNum":"${this.dataForm.salesPhoneNum}","Remark":"${
            this.dataForm.remark
          }","PayType":"${
            this.dataForm.payType.label || this.dataForm.payType
          }","AccountMoneyList":"","Discount":"","DiscountMoney":"","DiscountLastMoney":"","OtherMoney":""}`;
          let rows = `[
              ${this.dataForm.dataList
                .map((iitem) => {
                  console.log(iitem);
                  return `{"DepotId":"${
                    iitem.DepotName.id || iitem.DepotId
                  }","DepotName":"${
                    iitem.DepotName.depotName || iitem.DepotName
                  }","MaterialExtendId":"${
                    iitem.meId || iitem.MaterialExtendId
                  }","Stock":"${iitem.Stock || ""}","Unit":"${
                    iitem.unit
                  }","OperNumber":"${iitem.number}","UnitPrice":"${
                    iitem.lowDecimal
                  }","AllPrice":"${this.AllPrice || ""}","Remark":"${
                    iitem.remark
                  }"},`;
                })
                .join("")}
            ]`;
          this.$http({
            url: this.$http.adornUrl(
              `/depotHead/updateDepotHeadAndDetail?id=${this.$route.query.id}`
            ),
            method: "post",
            data: this.$http.adornData(
              {
                id: this.$route.query.id,
                info,
                preTotalPrice: this.AllPrice,
                rows,
              },
              false
            ),
          }).then((data) => {
            console.log(data);
            // this.visible = false;
            if (data.data.code === 0) {
              this.btnstatus = true;
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
              });
              this.$router.go(-1);
              this.removeTabHandle(this.mainTabsActiveName)
            } else {
              this.$message.error(data.msg);
            }
          });
        } else {
          console.log(this.dataForm.dateTime);
          let OperTime = this.timestampToTime(this.dataForm.dateTime.getTime());
          var salesDate = "";
          if (this.dataForm.salesDate) {
            salesDate = this.timestampToTime(this.dataForm.salesDate.getTime());
          }
          let info = `{"Type":"入库","SubType":"销售退货","DefaultNumber":"${
            this.dataForm.number
          }","Number":"${
            this.dataForm.number
          }","LinkNumber":"","salesDate":"${salesDate}","OperTime":"${OperTime}","OrganId":"${
            this.organId
          }","Salesman":"","AccountId":"${
            this.accountId || ""
          }","salesBillNo":"${this.dataForm.salesBillNo}","ChangeAmount":${
            this.AllPrice
          },"TotalPrice":"${this.AllPrice}","salesDate":"${
            this.dataForm.salesDate
          }","salesPhoneNum":"${
            this.dataForm.salesPhoneNum
          }","salesContacts":"${this.dataForm.salesContacts}","salesAddress":"${
            this.dataForm.salesAddress
          }","payType":"${
            this.dataForm.payType.label || ""
          }","transportType":""${
            this.dataForm.transportType.label || ""
          }"","serviceType":"${
            this.dataForm.serviceType.label || ""
          }","billType":"${
            this.dataForm.billType.label || ""
          }","deliveryBillNo":"${
            this.dataForm.deliveryBillNo
          }","deliverAddress":"${this.dataForm.address || ""}","contacts":"${
            this.dataForm.contacts
          }","phoneNum":"${this.dataForm.phoneNum}","Remark":"${
            this.dataForm.remark
          }","AccountMoneyList":"","Discount":"","username":"${
            this.dataForm.salesman.label || ""
          }","Discount":"","DiscountMoney":"","DiscountLastMoney":"","OtherMoney":"",externalNumber:"${
            this.dataForm.externalNumber
          }",trackingNumber:"${
            this.dataForm.trackingNumber
          }"}`;
          let rows = `[
              ${this.dataForm.dataList
                .map((iitem) => {
                  console.log(iitem);
                  return `{"DepotId":"${iitem.DepotName.id}","DepotName":"${
                    iitem.DepotName.depotName
                  }","MaterialExtendId":"${iitem.meId || ""}","Stock":"${
                    iitem.Stock || ""
                  }","Unit":"${iitem.unit}","OperNumber":"${
                    iitem.number
                  }","UnitPrice":"${iitem.lowDecimal}","AllPrice":"${
                    this.AllPrice || ""
                  }","Remark":"${iitem.remark}"},`;
                })
                .join("")}
            ]`;
          this.$http({
            url: this.$http.adornUrl(`/depotHead/addDepotHeadAndDetail`),
            method: "post",
            data: this.$http.adornData(
              {
                info,
                rows,
              },
              false
            ),
          }).then((data) => {
            if (data.data.code === 0) {
              this.btnstatus = true;
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
              });
              this.$router.go(-1);
              this.removeTabHandle(this.mainTabsActiveName)
            } else {
              console.log(data.data.msg);
              this.$message({
                message: `${data.data.msg}`,
                type: "error",
                duration: 1500,
              });
            }
          });
        }
      } else {
        this.$message({
          message: "请补全信息后重试",
          type: "warning",
          duration: 1500,
        });
      }
    },
    // 时间戳转成时间
    timestampToTime(timestamp) {
      var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + "-";
      var M =
        (date.getHours() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var D =
        (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      var h =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      var m =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":";
      var s =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return Y + M + D + h + m + s;
    },
    // 时间戳转成时间
    timestampToTime1(timestamp) {
      var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + "-";
      var M =
        (date.getHours() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var D = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      return Y + M + D;
    },
    // 返回上一目录
    goback() {
      this.$router.go(-1);
    },
    // 生单 其他入库
    gootherin() {
      sessionStorage.setItem("dataForm", JSON.stringify(this.dataForm));
      this.$router.push({
        path: "/warehouse-otherinlist/add",
      });
    },
    // 生单 其他出库
    gootherout() {
      sessionStorage.setItem("dataForm", JSON.stringify(this.dataForm));
      this.$router.push({
        path: "/warehouse-otheroutlist/add",
      });
    },
        // tabs, 删除tab
      removeTabHandle (tabName) {
        console.log(tabName)
        console.log(tabName)
        this.mainTabs = this.mainTabs.filter(item => item.name !== tabName)
        if (this.mainTabs.length >= 1) {
          // 当前选中tab被删除
          if (tabName === this.mainTabsActiveName) {
            var tab = this.mainTabs[this.mainTabs.length - 1]
            this.$router.push({ name: tab.name, query: tab.query, params: tab.params }, () => {
              this.mainTabsActiveName = this.$route.name
            })
          }
        } else {
          this.menuActiveName = ''
          this.$router.push({ name: 'home' })
        }
      },
  },
  computed: {
    AllPrice: {
      get: function () {
        let total = 0;
        if (this.dataForm.dataList.length == 0) {
          return;
        }
        this.dataForm.dataList.map((item) => {
          total += item.number * item.lowDecimal;
        });
        return total;
      },
      set: function () {
        return 0;
      },
    },
    mainTabsActiveName: {
        get () { return this.$store.state.common.mainTabsActiveName },
        set (val) { this.$store.commit('common/updateMainTabsActiveName', val) }
    },
    mainTabs: {
        get () { return this.$store.state.common.mainTabs },
        set (val) { this.$store.commit('common/updateMainTabs', val) }
    },
  },
};
</script>
<style scoped>
.el-card__body .listHead {
  margin-top: -20px;
  margin-bottom: 5px;
  border-bottom: 1px solid #eeeeee;
  font-size: 14px;
  display: flex;
  justify-content: space-between;
}
.el-form-item {
  width: 24%;
  justify-content: space-between;
  margin-bottom: 15px;
}
.el-form-item >>> .el-input {
  width: 220px;
}
.el-form-item >>> .el-form-item__content {
  display: flex;
}
.el-form-item >>> .el-form-item__content em {
  width: 100px;
  text-align: right;
  color: #31333d;
  margin-right: 15px;
  font-style: normal;
}
.block .el-date-editor .el-range-input {
  width: 50%;
}
.headInfo {
  margin-top: 20px;
}
.main >>> .el-table th,
.el-table tr {
  background-color: #F0F5FA;
  color: #31333D;
}
.customer i {
  position: absolute;
  right: 65px;
  top: 10px;
}
.customer {
  position: relative;
}
.main >>> .has-gutter tr td.el-table_1_column_2 .cell,
.main >>> .has-gutter tr td.el-table_1_column_5 .cell,
.main >>> .has-gutter tr td.el-table_1_column_7 .cell,
.main >>> .has-gutter tr td.el-table_1_column_9 .cell,
.main >>> .has-gutter tr td.el-table_1_column_8 .cell,
.main >>> .has-gutter tr td.el-table_1_column_12 .cell,
.main >>> .has-gutter tr td.el-table_1_column_11 .cell,
.main >>> .has-gutter tr td.el-table_1_column_3 .cell,
.main >>> .has-gutter tr td.el-table_1_column_4 .cell {
  display: none;
}
.footer {
  margin-top: 20px;
}
.form1 >>> .el-form-item {
  width: 100%;
  margin-top: 12px;
}
.form1 >>> .el-form-item .el-input {
  width: auto;
}
.el-form-item.is-required em:before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}
.el-dropdown-link {
  cursor: pointer;
  color: #0f63b8;
  margin: 0px 5px;
}
.el-icon-arrow-down {
  font-size: 12px;
}
.listHead >>> .el-button{
  width: 62px;
  height: 30px;
  line-height: 0px;
  background: #F2F9FF;
  border: 1px solid #3153C8;
  color: #3153C8;
  font-size: 14px;
}
.listHead >>> .el-button span{
  margin-left: -4px;
}
.listHead >>> .el-button:first-child{
  width: 62px;
  height: 30px;
  background: #3153C8;
  color: #fff;
}
.mod-user >>> .remarkFooter{
  width: 1617px;
  background: #F5F5F5;
  border: 1px solid #DDDDDD;
  border-radius: 4px;
  line-height: 40px;
  margin-top: 10px;
  margin-bottom: 10px;
  font-size: 14px;
  color: #666973;
  padding-left: 11px;
}
.main >>> .el-table__footer-wrapper tbody td,.main >>> .el-table__header-wrapper tbody td {
    background-color: #F0F5FA;
    color: #606266;
}
</style>
